package com.clusterswisdom.horn.servlet;

import java.io.File;
import java.util.Iterator;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.clusterswisdom.horn.api.db.DbUtil;
import com.clusterswisdom.horn.api.ioc.api.HornConfig;
import com.clusterswisdom.horn.api.quartz.ScheduleContext;

@WebListener
public class HornListener implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		String scope = sce.getServletContext().getInitParameter("scope");
		if (scope == null) {
			scope = HornConfig.SCOPE_RUNTIME;
		}
		HornConfig.getConfig().setScope(scope);
		
		String initDebug = sce.getServletContext().getInitParameter("initDebug");
		HornConfig.getConfig().setInitDebug("true".equals(initDebug));
		
		loadConfigProperties(sce);
		
		new ClassScaner().scanPackage(sce.getServletContext(), "com.clusterswisdom.horn.api");
		try {
			DbUtil.getUtil().init();
			
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		
		ScheduleContext.getContext().startScheduler();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {}
	
	private void loadConfigProperties(ServletContextEvent sce) {
		String configFile = sce.getServletContext().getRealPath("/WEB-INF/config/" + getConfigFile());
		try {
			Element root = new SAXReader().read(new File(configFile)).getRootElement();
			Iterator<Element> iterator = root.elementIterator();
			while (iterator.hasNext()) {
				Element element = (Element)iterator.next();
				HornConfig.getConfig().addProperty(element.getName(), element.getTextTrim());
			}
			
		} catch (DocumentException e) {
			e.printStackTrace();
			
		}
	}
	
	private String getConfigFile() {
		if (HornConfig.getConfig().isRuntime()) {
			return "config.xml";
			
		} else {
			return "config_" + HornConfig.getConfig().getScope() + ".xml";
			
		}
	}
}